//
//  AudioManager.m
//  ios-swift-pjsua2
//
//  Created by hollycrm on 2023/3/5.
//

#import "AudioManager.h"
#import "AudioHelper.h"

#import <UIKit/UIKit.h>
#import "wrapper.h"
#import <MediaPlayer/MediaPlayer.h>

#define IOSVersion [[UIDevice currentDevice].systemVersion floatValue]


@implementation AudioManager

@synthesize _isSpeakerOn;

@synthesize _isMicOn;



- (id)init

{

    self = [super init];

    if (self) {

        _isSpeakerOn = NO;
        _isMicOn = YES;

        AVAudioSession *audioSession = [AVAudioSession sharedInstance];

        //默认情况下扬声器播放

        [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth  error:nil];

        [audioSession setActive:YES error:nil];

    }

    return self;

}





static AudioManager *_audioManager = NULL;

+(AudioManager*)shared

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _audioManager = [[AudioManager alloc] init];

    });

    return _audioManager;

}

- (void)openMic{
    [[[CPPWrapper alloc] init] setMicOn:true];
    _isMicOn = true;
}
-(void)closeMic{
    [[[CPPWrapper alloc] init] setMicOn:false];
    _isMicOn = false;
}

- (void)setSpeakerOn

{
 //[[CPPWrapper new] setSpeakerOn:true];
    [self setSpeakerEnabled:true];
}

- (void)setSpeakerOff
{
 //[[CPPWrapper new] setSpeakerOn:false];
    [self setSpeakerEnabled:false];
}

-(BOOL)allowSpeaker{
    
    bool allow = true;
    AVAudioSessionRouteDescription *newRoute = [AVAudioSession sharedInstance].currentRoute;
    if (newRoute) {
        if (newRoute.outputs.count > 0){
            NSString *route = newRoute.outputs[0].portType;
            allow = !([route isEqualToString:AVAudioSessionPortLineOut] ||
                      [route isEqualToString:AVAudioSessionPortHeadphones] ||
                      [[AudioHelper bluetoothRoutes] containsObject:route]);
        }
    }
    return allow;
}

-(void)releaseSound{
    NSError *err = nil;
    [[AVAudioSession sharedInstance] setActive:false error:&err];
}

- (void)setSpeakerEnabled:(BOOL)enable {
    _isSpeakerOn = enable;
    NSError *err = nil;
    if (enable) {
        if ([self allowSpeaker]){
            [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&err];
            [[AVAudioSession sharedInstance] setActive:true error:&err];
            
        }
    } else {
        [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&err];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&err];
        [[AVAudioSession sharedInstance] setActive:true error:&err];
    
    }

    if (err) {
       
    }
}


// 推断麦克风是否实用

- (BOOL)hasMicphone

{
    return [[AVAudioSession sharedInstance] isInputAvailable];
}


void audioRouteChangeListenerCallback (void *inUserData, AudioSessionPropertyID inPropertyID, UInt32 inPropertyValueS, const void *inPropertyValue)

{

    if (inPropertyID != kAudioSessionProperty_AudioRouteChange)

        return;

    

    // Determines the reason for the route change, to ensure that it is not

    // because of a category change.

    CFDictionaryRef routeChangeDictionary = (CFDictionaryRef)inPropertyValue;

    

    CFNumberRef routeChangeReasonRef = (CFNumberRef)CFDictionaryGetValue (routeChangeDictionary, CFSTR (kAudioSession_AudioRouteChangeKey_Reason));

    

    SInt32 routeChangeReason;

    

    CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);

   // NSLog(@"<<<RouteChangeReason: %d",(int)routeChangeReason);

   // NSLog(@"[=======%@",inUserData);

    

    AudioManager *pMgr = (__bridge AudioManager *)inUserData;

    //没有耳机

    if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)

    {

        [pMgr setSpeakerOn];

    }

    else if (routeChangeReason == kAudioSessionRouteChangeReason_NewDeviceAvailable)

    {

       

    }else if (routeChangeReason == kAudioSessionRouteChangeReason_Override){
        

    }


        if (routeChangeReason==8) {


        }


}

- (void)setSystemVolumeTo:(float)value {
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    UISlider *slider = nil;

    // 查找 MPVolumeView 中的 UISlider
    for (UIView *view in volumeView.subviews) {
        if ([view isKindOfClass:[UISlider class]]) {
            slider = (UISlider *)view;
            break;
        }
    }

    if (!slider) {
        return; // 如果没有找到 slider，直接返回
    }

    // 异步调整音量（需在主线程操作）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        slider.value = value;
    });
}

@end
